#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
ManageMyself API 测试脚本
用于验证所有API配置是否正常工作
"""

import requests
import json
import sys

# API配置
WEATHER_API_URL = "https://cn.apihz.cn/api/tianqi/tqyb.php"
WEATHER_API_ID = "88888888"
WEATHER_API_KEY = "88888888"

TIANAPI_URL = "https://apis.tianapi.com/lunar/index"
TIANAPI_KEY = "03f2cc3b8aff57185173c0862442743b"

DEEPSEEK_API_URL = "https://api.deepseek.com/v1/chat/completions"
DEEPSEEK_API_KEY = "sk-aaa6320f47554c5eb46185826e7f9cd7"

def test_weather_api():
    """测试天气API"""
    print("🌤️ 测试天气API...")
    
    params = {
        'id': WEATHER_API_ID,
        'key': WEATHER_API_KEY,
        'sheng': '北京',
        'place': '朝阳'
    }
    
    try:
        response = requests.get(WEATHER_API_URL, params=params, timeout=10)
        response.raise_for_status()
        
        data = response.json()
        print(f"✅ 天气API测试成功!")
        print(f"   地点: {data.get('place', 'N/A')}")
        print(f"   温度: {data.get('temperature', 'N/A')}")
        print(f"   湿度: {data.get('humidity', 'N/A')}")
        print(f"   风向: {data.get('windDirection', 'N/A')}")
        return True
        
    except requests.exceptions.RequestException as e:
        print(f"❌ 天气API测试失败: {e}")
        return False
    except json.JSONDecodeError as e:
        print(f"❌ 天气API响应解析失败: {e}")
        return False

def test_tianapi():
    """测试天行API"""
    print("\n📅 测试天行API...")
    
    params = {
        'key': TIANAPI_KEY
    }
    
    try:
        response = requests.get(TIANAPI_URL, params=params, timeout=10)
        response.raise_for_status()
        
        data = response.json()
        if data.get('code') == 200:
            result = data.get('result', {})
            print(f"✅ 天行API测试成功!")
            print(f"   公历日期: {result.get('gregoriandate', 'N/A')}")
            print(f"   农历日期: {result.get('lunardate', 'N/A')}")
            print(f"   宜: {result.get('fitness', 'N/A')[:50]}...")
            print(f"   忌: {result.get('taboo', 'N/A')[:50]}...")
            return True
        else:
            print(f"❌ 天行API返回错误: {data.get('msg', 'Unknown error')}")
            return False
            
    except requests.exceptions.RequestException as e:
        print(f"❌ 天行API测试失败: {e}")
        return False
    except json.JSONDecodeError as e:
        print(f"❌ 天行API响应解析失败: {e}")
        return False

def test_deepseek_api():
    """测试DeepSeek API"""
    print("\n🤖 测试DeepSeek API...")
    
    headers = {
        'Authorization': f'Bearer {DEEPSEEK_API_KEY}',
        'Content-Type': 'application/json'
    }
    
    data = {
        'model': 'deepseek-chat',
        'messages': [
            {'role': 'user', 'content': '你好，请用一句话介绍你自己'}
        ],
        'max_tokens': 100
    }
    
    try:
        response = requests.post(DEEPSEEK_API_URL, headers=headers, json=data, timeout=30)
        response.raise_for_status()
        
        result = response.json()
        if 'choices' in result and len(result['choices']) > 0:
            message = result['choices'][0]['message']['content']
            print(f"✅ DeepSeek API测试成功!")
            print(f"   AI回复: {message}")
            return True
        else:
            print(f"❌ DeepSeek API响应格式错误: {result}")
            return False
            
    except requests.exceptions.RequestException as e:
        print(f"❌ DeepSeek API测试失败: {e}")
        return False
    except json.JSONDecodeError as e:
        print(f"❌ DeepSeek API响应解析失败: {e}")
        return False

def main():
    """主函数"""
    print("🔧 ManageMyself API 配置测试")
    print("=" * 50)
    
    results = []
    
    # 测试所有API
    results.append(test_weather_api())
    results.append(test_tianapi())
    results.append(test_deepseek_api())
    
    # 输出总结
    print("\n" + "=" * 50)
    print("📊 测试结果总结:")
    
    success_count = sum(results)
    total_count = len(results)
    
    if success_count == total_count:
        print(f"🎉 所有API测试通过! ({success_count}/{total_count})")
        sys.exit(0)
    else:
        print(f"⚠️  部分API测试失败! ({success_count}/{total_count})")
        sys.exit(1)

if __name__ == "__main__":
    main() 